﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BizzCommInterfaces;
using System.Windows.Forms;
using System.IO;

namespace FileTrays
{
    public class FileInbox : Tray, IInbox
    {
        //private const string _name = "FileInboxProvider";
        private const char _separator = ';';
        public string folder { get; set; }
        private string lastFile { get; set; }
        //private string concreteInboxName;

        public FileInbox()
        {
            lastFile = null;
            folder = null;
            base._name = "FileInboxProvider";
        }

        #region IInbox Members

        public void getConfigurationWindow()
        {
            FileInboxConfigControl configControl = new FileInboxConfigControl(this);
            configControl.ShowDialog();
        }

        public int getCount()
        {
            var files = Directory.GetFiles(folder).Where(name => name.EndsWith(".txt"));
            return files.Count();
        }

        public void markAsRead()
        {
            File.Delete(lastFile);
            lastFile = null;
        }

        //BRAND NEW ----------------------------------------------------------------------------------
        public string getWorkingMessage()
        {
            string workingMsg = null;
            var files = from f in Directory.GetFiles(folder).Where(name => name.EndsWith(".txt"))
                        orderby f ascending
                        select f;

            if (files != null)
            {
                lastFile = files.First();
                workingMsg = lastFile;
            }
            return workingMsg;
        }
        //END BRAND NEW ----------------------------------------------------------------------------------

      /*  public BizzMessage readMessage()
        {
            BizzMessage msg = null;
            var files = from f in Directory.GetFiles(folder).Where(name => name.EndsWith(".txt"))
                        orderby f ascending
                        select f;

            if (files != null)
            {
                lastFile = files.First();
                msg = readFile(lastFile);

            }
            return msg;
        }*/

        public BizzMessage readMessage(string messageToRead)
        {
            BizzMessage msg = null;
            if (messageToRead != null)
            {
                msg = readFile(lastFile);
                if (msg.Title == null)
                {
                    throw new Exception("Mensaje mal formado");
                }
            }
            return msg;
        }

        private BizzMessage readFile(string lastFile)
        {
            //Initialize the message to be returned
            BizzMessage retMessage = new BizzMessage();
            retMessage.Attributes = new List<MsgAttribute>();

            //Access and read the file
            using (FileStream fs = new FileStream(lastFile, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                List<string> list = new List<string>();
                StreamReader reader = new StreamReader(fs);
                string line;
                if ((line = reader.ReadLine()) != null)
                {
                    //Build the message to be returned
                    //1- Set the title
                    retMessage.Title = line;

                    //2- Set the attributes
                    while ((line = reader.ReadLine()) != null)
                    {
                        String[] strAtt = line.Split(';');
                        MsgAttribute msgAtt = new MsgAttribute();

                        msgAtt.Name = strAtt[0];
                        msgAtt.Type = retMessage.getMsgType(strAtt[1]);
                        msgAtt.Value = strAtt[2];
                        retMessage.Attributes.Add(msgAtt);
                    }
                }
                reader.Close();
                fs.Close();
            }
            return retMessage;
        }


        public string codeMe()
        {
            string ret = folder + _separator + lastFile + _separator + _concreteName;
            return ret;
        }

        public void decodeMe(string box)
        {
            string[] attr = box.Split(_separator);
            folder = attr[0];
            lastFile = attr[1];
            _concreteName = attr[2];
        }

        #endregion


        public string getInboxName()
        {
            return _name;
        }


        public string[] getDescription()
        {
            string[] ret = new string[8];
            ret[0] = "Direcotrio Texto. Cada mensaje será un archivo txt";
            ret[1] = "en el directorio que se seleccione.";
            ret[2] = "El formato del txt será:";
            ret[3] = "";
            ret[4] = "este es el titulo del mensaje";
            ret[5] = "Apellido;Texto;Perez";
            ret[6] = "Edad;Numero;30";
            ret[7] = "Casado;Booleano;True";
   
            return ret;
        }

        public bool isReady()
        {
            return (folder != null);
        }





        #region IInbox Members


        public string getConcreteInboxName()
        {
            return getConcreteName();
        }

        public void setConcreteInboxName(string name)
        {
            _concreteName = name;
        }

        #endregion
    }
}
